package com.example.concurrent.threadpool;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程工厂，它设置线程名称，有利于我们定位问题。
 */
public class NamingThreadFactory implements ThreadFactory {
    private final AtomicInteger threadNum = new AtomicInteger(1);
    private ThreadFactory delegate;  //代理线程工厂 ，创建线程用的是 delegate，
    private String name;    //线程名前缀
    /**
     * 创建一个带名字的线程池生产工厂
     */
    public NamingThreadFactory(ThreadFactory delegate,String name) {
        this.delegate = delegate;
        this.name = name;
    }

    /**
     * 重写 newThread 方法创建一个线程，调用的是 delegate 的 newThread 方法，我们只是在了线程的名字
     * @param r Runnable
     * @return 线程
     */
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = delegate.newThread(r);
        thread.setName(name + "-" + threadNum.getAndIncrement());
        return thread;
    }
}
